﻿using SmartPlant.WinCore;
using System.Windows;

namespace SmartPlan.TelerikExt
{
    /// <summary>
    /// 权限检查。
    /// </summary>
    public class PermissionControl
    {
        // 定义附加属性
        public static readonly DependencyProperty IsEnableByPermissionProperty =
            DependencyProperty.RegisterAttached(
                "IsEnableByPermission",
                typeof(string),
                typeof(PermissionControl),
                new FrameworkPropertyMetadata("admin", FrameworkPropertyMetadataOptions.AffectsRender, OnIsEnableByPermissionChanged));

        // 提供 getter 和 setter 方法
        public static string GetIsEnableByPermission(FrameworkElement element)
        {
            return (string)element.GetValue(IsEnableByPermissionProperty);
        }

        public static void SetIsEnableByPermission(FrameworkElement element, string value)
        {
            element.SetValue(IsEnableByPermissionProperty, value);

        }

        // 当属性值改变时触发的方法
        private static void OnIsEnableByPermissionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement uiElement && !string.IsNullOrEmpty(e.NewValue as string))
            {
                //var functionId = e.NewValue.ToInt();
                var functionName = (string)uiElement.GetValue(IsEnableByPermissionProperty);
                uiElement.Loaded += (object sender, RoutedEventArgs e) =>
                {
                    uiElement.IsEnabled = GetRight(functionName);
                };
            }
        }

        private static bool GetRight(string functionName)
        {
            if (GlobalObject.isSysAdminUser.Equals("1", StringComparison.CurrentCultureIgnoreCase))
                return true;
             
            var funciton = GlobalObject.UserRightDatas?.FirstOrDefault(userData => userData.FunctionName == functionName && userData.PpauId == GlobalObject.CurrentUnit.UnitId.ToString());
            return funciton != null && funciton.IsEnabled == 1;
        }
    }
}
